package com.atguigu.srb.core.controller;


import com.alibaba.fastjson.JSON;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.pojo.entity.TransFlow;
import com.atguigu.srb.core.service.TransFlowService;
import com.atguigu.srb.core.service.UserAccountService;
import com.atguigu.srb.core.util.JwtUtils;
import com.atguigu.srb.result.R;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;

/**
 * <p>
 * 用户账户 前端控制器
 * </p>
 *
 * @author fun
 * @since 2021-10-29
 */
@RestController
@RequestMapping("/api/core/userAccount")
public class UserAccountController {
    @Autowired
    UserAccountService userAccountService;
    @Autowired
    TransFlowService transFlowService;

    @PostMapping("/auth/commitCharge/{chargeAmt}")
    public R commitCharge(@PathVariable("chargeAmt") BigDecimal chargeAmt, HttpServletRequest request) {
        String token = request.getHeader("token");
        if (!StringUtils.isEmpty(token)) {
            Long userId = JwtUtils.getUserId(token);
            System.out.println(userId);
            // 根据api生成formStr
            String formStr = userAccountService.commitCharge(chargeAmt, userId);
            return R.ok().data("formStr", formStr);
        } else {
            return R.error();
        }
    }

    @PostMapping("/notify")
    public String notify(HttpServletRequest request) {
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, Object> stringObjectMap = RequestHelper.switchMap(request.getParameterMap());
        String agentBillNo = (String) stringObjectMap.get("agentBillNo");
        //判断交易流水是否存在
        Boolean isSave = transFlowService.isSaveTransFlow(agentBillNo);
        if (isSave) {
            userAccountService.hfbNotify(stringObjectMap);
        }
        return "success";
    }

    @GetMapping("/auth/getAccount")
    public R getAccount(HttpServletRequest request) {
        String token = request.getHeader("token");
        if (!StringUtils.isEmpty(token)) {
            Long userId = JwtUtils.getUserId(token);
            BigDecimal account = userAccountService.getAccount(userId);
            return R.ok().data("account", account);
        } else {
            return R.error();
        }
    }
}

